<template>
  <div class="queue-page">
    <!-- 导航栏 -->
    <van-nav-bar
      title="排队信息"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
      class="nav-bar"
    />

    <!-- 就诊人信息 -->
    <van-cell class="patient-cell">
      <template #title>
        <span class="label">当前就诊人</span>
        <span class="value">{{ defaultPatient?.name || '未设置' }}</span>
      </template>
      <van-button 
        size="small" 
        type="primary" 
        round 
        @click="showDetails = true"
      >
        详情
      </van-button>
    </van-cell>

    <!-- 加载状态 -->
    <van-loading v-if="loading" vertical size="36">
      <div class="loading-text">加载排队信息中...</div>
    </van-loading>

    <!-- 核心排队信息区 -->
    <div v-if="!loading && queueInfo && queueInfo.length > 0" class="core-info">
      <!-- 显示所有排队记录 -->
      <div v-for="(queue, index) in queueInfo" :key="index" class="info-card">
        <div class="card-header">
          <span class="card-title">排队记录 {{ index + 1 }}</span>
          <span class="update-time">更新于 {{ updateTime }}</span>
        </div>
        
        <div class="queue-core">
          <div class="queue-item">
            <span class="queue-label">您的就诊号</span>
            <span class="queue-value">{{ getVisitNoText(queue) }}</span>
          </div>
          
          <div class="queue-item">
            <span class="queue-label">就诊时间段</span>
            <span class="queue-value">{{ getTimeSlotWithTime(queue) }}</span>
          </div>
          
          <div class="queue-item">
            <span class="queue-label">前面等待人数</span>
            <span class="queue-value highlight">{{ getWaitingCount(queue) }}</span>
          </div>
          
          <div class="queue-item">
            <span class="queue-label">预计等待时间</span>
            <span class="queue-value">{{ getEstimatedWaitTime(queue) }}</span>
          </div>
        </div>
        
        <!-- 进度条 -->
        <div class="progress-container">
          <van-progress 
            :percentage="calculateProgress(queue)" 
            :show-pivot="false"
            color="#07c160"
            stroke-width="8"
          />
          <div class="progress-stats">
            <span>已就诊: {{ getProcessedCount(queue) }}人</span>
            <span>总人数: {{ queue.total_quota }}人</span>
          </div>
        </div>
        
        <!-- 操作按钮区 -->
        <div class="action-buttons">
          <van-button 
            type="primary" 
            round 
            class="action-btn"
            @click="showNavigationForQueue(queue)"
          >
            <van-icon name="location-o" class="btn-icon" />
            诊室导航
          </van-button>
          <van-button 
            type="info" 
            round 
            class="action-btn"
            @click="setReminderForQueue(queue)"
          >
            <van-icon name="bell-o" class="btn-icon" />
            叫号提醒
          </van-button>
        </div>
      </div>
    </div>

    <!-- 无数据状态 -->
    <div v-if="!loading && (!queueInfo || queueInfo.length === 0)" class="empty-state">
      <van-empty 
        image="search" 
        description="暂无排队信息"
      >
        <van-button 
          type="primary" 
          round 
          @click="fetchQueueData"
        >
          重新获取
        </van-button>
      </van-empty>
    </div>

    <!-- 详情弹窗 -->
    <van-dialog
      v-model:show="showDetails"
      title="就诊详情"
      width="90%"
    >
      <div class="detail-content">
        <van-cell title="就诊人" :value="defaultPatient?.name || '未设置'" />
        <van-cell title="身份证号" :value="defaultPatient?.id_card || '未设置'" />
        <van-cell title="联系电话" :value="defaultPatient?.phone || '未设置'" />
      </div>
    </van-dialog>

    <!-- 导航弹窗 -->
    <van-dialog
      v-model:show="showNavigation"
      title="诊室导航"
      width="90%"
    >
      <div class="navigation-content">
        <div class="map-placeholder">
          <van-icon name="location-o" size="48" color="#07c160" />
          <div class="map-text">{{ currentQueue?.dept_location || '诊室位置信息未提供' }}</div>
          	    
		  
        </div>
        <div class="navigation-steps">
       
		  
		  <div class="step-item">1. 从当前位置前往电梯厅</div>
		  <div class="step-item">2. 乘坐电梯至{{ getFloorFromLocation(currentQueue?.dept_location) || '目标' }}层</div>
		  <div class="step-item ">3. 根据指示牌找到诊室</div>
		  	    
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
// 依赖导入
import { ref, onMounted, getCurrentInstance, onUnmounted } from 'vue';
import { showToast, showFailToast, showSuccessToast } from 'vant';
import { useUserStore } from '../stores/user.js';

// 状态管理与初始化
const userStore = useUserStore();
const { proxy } = getCurrentInstance(); // 获取Vue实例代理
const queueInfo = ref([]); // 排队信息数组
const currentQueueStatus = ref({}); // 当前叫号状态，键为schedule_id
const loading = ref(true); // 加载状态
const defaultPatient = ref(userStore.defaultPatient); // 默认就诊人
const showDetails = ref(false); // 详情弹窗显示状态
const showNavigation = ref(false); // 导航弹窗显示状态
const currentQueue = ref(null); // 当前操作的排队记录
const updateTime = ref(''); // 数据更新时间
const refreshTimer = ref(null); // 定时刷新计时器

// 辅助方法 - 从位置信息中提取楼层
const getFloorFromLocation = (location) => {
  if (!location) return '';
  // 匹配"X层"这样的文本，如"4层"
  const match = location.match(/(\d+)层/);
  return match ? match[1] : '';
};




// 时间格式化工具
const formatTimeStr = (timeStr) => {
  if (!timeStr) return '';
  // 处理包含秒的时间格式，如"09:43:51"，只保留时分
  const timeParts = timeStr.split(':');
  if (timeParts.length >= 2) {
    return `${timeParts[0]}:${timeParts[1]}`;
  }
  return timeStr;
};

const formatTime = () => {
  const now = new Date();
  return now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
};

// 辅助方法 - 获取时间槽文本
const getTimeSlotText = (queue) => {
  if (!queue) return '';
  const timeSlots = ['', '上午', '下午', '晚上'];
  return timeSlots[queue.time_slot] || '';
};

// 辅助方法 - 获取带时间段的文本
const getTimeSlotWithTime = (queue) => {
  if (!queue) return '';
  const timeSlot = getTimeSlotText(queue);
  if (!timeSlot) return '';
  
  const startTime = formatTimeStr(queue.start_time);
  const endTime = formatTimeStr(queue.end_time);
  
  if (startTime && endTime) {
    return `${timeSlot} ${startTime}-${endTime}`;
  }
  return timeSlot;
};

// 辅助方法 - 获取就诊号文本
const getVisitNoText = (queue) => queue?.visit_no || '未分配';

// 辅助方法 - 获取当前叫号
const getCurrentQueueNumber = (queue) => {
  if (!queue || !currentQueueStatus.value[queue.schedule_id]) return '等待叫号';
  return currentQueueStatus.value[queue.schedule_id].current_queue_number || '等待叫号';
};

// 辅助方法 - 获取已处理人数
const getProcessedCount = (queue) => {
  if (!queue || !currentQueueStatus.value[queue.schedule_id]) return 0;
  return currentQueueStatus.value[queue.schedule_id].processed_count || 0;
};

// 辅助方法 - 获取等待人数
const getWaitingCount = (queue) => {
  // 数据不完整时显示计算中
  if (!queue?.visit_no || !currentQueueStatus.value[queue.schedule_id]?.current_queue_number) {
    return '计算中...';
  }
  
  // 提取号码数字部分并计算等待人数
  const currentNo = parseInt(currentQueueStatus.value[queue.schedule_id].current_queue_number.replace(/\D/g, '')) || 0;
  const myNo = parseInt(queue.visit_no.replace(/\D/g, '')) || 0;
  const count = Math.max(0, myNo - currentNo);
  
  // 即将到号提醒
  if (count <= 2 && count >= 0) {
    showToast({
      message: `【排队${queue.visit_no}】即将到您就诊（还剩${count}人）`,
      position: 'top',
      duration: 3000,
    });
  }
  
  return count;
};

// 计算排队进度百分比
const calculateProgress = (queue) => {
  if (!queue?.total_quota) return 0;
  const processed = getProcessedCount(queue);
  return Math.round((processed / queue.total_quota) * 100);
};

// 计算预计等待时间
const getEstimatedWaitTime = (queue) => {
  const waiting = getWaitingCount(queue);
  if (waiting === '计算中...') return '计算中...';
  const minutes = waiting * 5; // 假设每人5分钟
  if (minutes <= 0) return '即将就诊';
  if (minutes < 60) return `约${minutes}分钟`;
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return `约${hours}小时${remainingMinutes}分钟`;
};

// 核心方法 - 获取排队数据
const fetchQueueData = async () => {
  // 校验就诊人信息
  if (!defaultPatient.value?.patient_id) {
    loading.value = false;
    showToast('请先设置默认就诊人');
    return;
  }
  
  loading.value = true;
  try {
    // 1. 获取就诊人所有排队信息
    const patientResponse = await proxy.$axios.get(
      `/api/v1/queue/showQueue/${defaultPatient.value.patient_id}`
    );
    
    if (patientResponse.data.code === 0 && patientResponse.data.data.length > 0) {
      queueInfo.value = patientResponse.data.data;
      
      // 2. 为每个排队记录获取当前叫号状态
      for (const queue of queueInfo.value) {
        const queueResponse = await proxy.$axios.get(
          `/api/v1/queue/showQueueAndMy/${queue.schedule_id}`
        );
        
        if (queueResponse.data.code === 0) {
          currentQueueStatus.value[queue.schedule_id] = {
            current_queue_number: queueResponse.data.data[0]?.visit_no || '',
            processed_count: queueResponse.data.data.length || 0
          };
        }
      }
      
      // 更新时间戳
      updateTime.value = formatTime();
    } else {
      queueInfo.value = [];
    }
  } catch (error) {
    console.error('获取排队信息失败:', error);
    showFailToast('获取排队信息失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 叫号提醒设置
const setReminderForQueue = (queue) => {
  showSuccessToast(`排队号${queue.visit_no}的叫号提醒已开启`);
  // 实际项目中可在此处调用推送服务API
};

// 显示导航弹窗
const showNavigationForQueue = (queue) => {
  currentQueue.value = queue;
  showNavigation.value = true;
};

// 定时刷新控制
const startRefreshTimer = () => {
  // 每分钟自动刷新一次数据
  refreshTimer.value = setInterval(fetchQueueData, 60000 );
};

// 生命周期管理
onMounted(() => {
  // 初始化时加载数据并启动定时刷新
  if (defaultPatient.value) {
    fetchQueueData();
    startRefreshTimer();
  } else {
    loading.value = false;
  }
});

onUnmounted(() => {
  // 页面销毁时清除定时器
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
  }
});

</script>


<style scoped>
.queue-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.nav-bar {
  background-color: #ffffff;
}

.patient-cell {
  background-color: #fff;
  margin-bottom: 10px;
  padding: 12px 16px;
}

.label {
  color: #666;
  margin-right: 8px;
  font-size: 15px;
}

.value {
  font-weight: 500;
  font-size: 16px;
  color: #333;
}

.loading-text {
  margin-top: 12px;
  color: #666;
}

.core-info {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 16px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
}

.info-card:active {
  transform: scale(0.99);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f5f5f5;
}

.card-title {
  font-size: 17px;
  font-weight: 600;
  color: #333;
}

.update-time {
  font-size: 12px;
  color: #999;
}

.queue-core {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
  margin-bottom: 16px;
}

.queue-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.queue-item:last-child {
  border-bottom: none;
}

.queue-label {
  color: #666;
  font-size: 15px;
}

.queue-value {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  text-align: right;
}

.highlight {
  color: #07c160;
  font-size: 18px;
  font-weight: 600;
}

.progress-container {
  margin-top: 16px;
}

.progress-stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}

.action-btn {
  flex: 1;
  padding: 10px 0;
  font-size: 15px;
}

.btn-icon {
  margin-right: 6px;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.detail-content {
  padding-top: 10px;
}

.navigation-content {
  padding: 10px 0;
}

.map-placeholder {
  background-color: #f5f5f5;
  height: 160px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
}

.map-text {
  margin-top: 12px;
  color: #333;
  font-size: 15px;
}

.navigation-steps {
  padding-left: 8px;
}

.step-item {
  padding: 8px 0;
  position: relative;
  font-size: 14px;
  color: #333;
}

.step-item::before {
  content: '';
  position: absolute;
  left: -8px;
  top: 16px;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #07c160;
}

/* 适配不同屏幕尺寸 */
@media (min-width: 375px) {
  .action-btn {
    font-size: 16px;
  }
}

@media (min-width: 414px) {
  .core-info {
    padding: 20px;
  }
  
  .info-card {
    padding: 20px;
  }
}
</style>
